
// pages/create/create.js
Page({
  data: {
    currentLyric: '',
    prevLyric: '',
    nextLyric: '',
    currentLine: 1,
    songs: [{
      id: 1,
      name: '致橡树(Piano ver.)',
      lyrics: [
        '每一阵风过',
        '我们都相互致意',
        '但没有人听懂我们的言语'
      ]
    }],
    currentSongIndex: 0,
    currentLyricIndex: 0
  },

  onLoad(options) {
    this.initLyrics();
  },

  onUnload() {
  },

  initLyrics() {
    const lyrics = this.data.songs[this.data.currentSongIndex].lyrics;
    this.setData({
      prevLyric: lyrics[0] || '',
      currentLyric: lyrics[1] || '',
      nextLyric: lyrics[2] || '',
      currentLine: 1,
      currentLyricIndex: 1
    });
  },

  // 添加防抖标志
  isNavigating: false,

  navigateToDetail() {
    // 防止重复点击
    if (this.isNavigating) {
      return;
    }
    
    // 设置导航状态
    this.isNavigating = true;
    
    // 显示加载中提示
    wx.showLoading({
      title: '加载中...',
      mask: true // 使用遮罩防止用户点击
    });

    const that = this;
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['.json'],
      success(res) {
        const tempFilePaths = res.tempFiles[0].path;
        const fs = wx.getFileSystemManager();
        fs.readFile({
          filePath: tempFilePaths,
          encoding: 'utf8',
          success(data) {
            try {
              const jsonData = JSON.parse(data.data);
              // 验证数据格式是否与localData一致
              if (!jsonData.FirstData || !jsonData.ChatData || !jsonData.CardData) {
                throw new Error('JSON文件格式不符合要求，必须包含FirstData、ChatData和CardData字段');
              }
              wx.navigateTo({
                url: '/pages/detail/detail',
                success: function(res) {
                  console.log('解析成功');
                  res.eventChannel.emit('updateData', jsonData);
                },
                fail: (err) => {
                  console.error('跳转失败:', err);
                  wx.showToast({
                    title: '跳转失败',
                    icon: 'none'
                  });
                },
                complete: () => {
                  wx.hideLoading();
                  setTimeout(() => {
                    that.isNavigating = false;
                  }, 500);
                }
              });
            } catch (e) {
              console.error('解析JSON失败:', e);
              that.useLocalData();
            }
          },
          fail() {
            that.useLocalData();
          }
        });
      },
      fail() {
        that.useLocalData();
      }
    });
  },

  useLocalData() {
    wx.navigateTo({
      url: '/pages/detail/detail',
      success: function(res) {
        console.log('跳转成功');
      },
      fail: (err) => {
        console.error('跳转失败:', err);
        wx.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
        setTimeout(() => {
          this.isNavigating = false;
        }, 500);
      }
    });
  }
});